﻿using DevExpress.Utils.Drawing;
using DevExpress.XtraBars.Ribbon;
using Kaliko.ImageLibrary;
using Kaliko.ImageLibrary.Filters;
using Kaliko.ImageLibrary.Scaling;
using Karbel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
using Trimmer.Utility;

namespace Trimmer
{
    public class A
    {
        public int AksesuarId;
        public string AksSeriId;
        public string Kategori;
    }

    public partial class Liste : Form
    {
        public Liste()
        {
            InitializeComponent();
        }

        string id = string.Empty;
        string targetDirectory = @"D:\AksPhoto";
        string targetDirectoryR = @"D:\AksPhoto.rect";
        string newDirectory = @"D:\AksPhoto.Cropped";
        string hueDirectory = @"D:\AksPhoto.hue";

        private void Liste_Load(object sender, EventArgs e)
        {
            this.Visible = false;

            using (Login login = new Login())
            {
                DialogResult dr = login.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    this.Visible = true;

                    AppSession appSession = new AppSession();
                    AppSession.DataManager = new DataManager(login.ConnectionString);
                }
                else
                    Application.Exit();
            }

            btnCrop.Click += btnCrop_Click;
            GetStatus();


            gc = new GalleryControl();
            gc.Dock = DockStyle.Fill;
            this.Controls.Add(gc);

            gc.Gallery.ItemImageLayout = ImageLayoutMode.ZoomInside;
            gc.Gallery.ImageSize = new Size(120, 90);
            gc.Gallery.ShowItemText = true;

            group1 = new GalleryItemGroup();
            group1.Caption = "Garment";
            gc.Gallery.Groups.Add(group1);


        }
        GalleryControl gc;
        GalleryItemGroup group1;

        void btnShow_Click(object sender, EventArgs e)
        {
            List();
        }

        string selSeri = string.Empty;
        string selKategori = string.Empty;
        List<string> Kat = new List<string>();
        List<string> Seri = new List<string>();
        Dictionary<string, A> Sira = new Dictionary<string, A>();

        Dictionary<string, Rectangle> listR = new Dictionary<string, Rectangle>();
        List<string> listF = new List<string>();

        string GetFN(string fileName)
        {
            return System.IO.Path.GetFileNameWithoutExtension(fileName);
        }

        void GetStatus()
        {
            string[] fileEntries = Directory.GetFiles(targetDirectory);
            foreach (string fileName in fileEntries)
                listF.Add(GetFN(fileName));

            fileEntries = Directory.GetFiles(targetDirectoryR);
            foreach (string fileName in fileEntries)
                using (StreamReader reader = new StreamReader(fileName))
                {
                    string[] r = reader.ReadLine().Split(",".ToCharArray());
                    string id = GetFN(fileName);

                    listR.Add(id, new Rectangle(int.Parse(r[0]), int.Parse(r[1]), int.Parse(r[2]), int.Parse(r[3])));
                }

            listF.Sort();


            DataTable dt = AppSession.DataManager.ExecuteDataTable("GetAksSira");
            foreach (DataRow r in dt.Rows)
            {
                string S = r["Sira"].ToString();
                string Ktg = r["Kategori"].ToString();
                string Se = r["AksSeriId"].ToString();
                int Id = (int)r["AksesuarId"];

                if (!Kat.Contains(Ktg))
                    Kat.Add(Ktg);

                A oA = new A();
                oA.AksesuarId = Id;
                oA.AksSeriId = Se;
                oA.Kategori = Ktg;

                if (!Sira.ContainsKey(S))
                    Sira.Add(S, oA);

                if (Se != "0")
                    if (!Seri.Contains(Se))
                        Seri.Add(Se);
            }

            Kat.Sort();
            Seri.Sort();

            comboBoxKategori.Items.AddRange(Kat.ToArray());
            comboBoxSeri.Items.AddRange(Seri.ToArray());

            comboBoxKategori.SelectedIndexChanged += comboBoxKategori_SelectedIndexChanged;
            comboBoxSeri.SelectedIndexChanged += comboBoxSeri_SelectedIndexChanged;

        }

        void comboBoxSeri_SelectedIndexChanged(object sender, EventArgs e)
        {
            selKategori = string.Empty;
            selSeri = comboBoxSeri.SelectedItem.ToString();
            List();
        }

        void comboBoxKategori_SelectedIndexChanged(object sender, EventArgs e)
        {
            selKategori = comboBoxKategori.SelectedItem.ToString();
            selSeri = string.Empty;
            List();
        }

        void List()
        {
            int x = 0;
            flowLayoutPanel1.Controls.Clear();
            flowLayoutPanel1.Visible = false;
            GC.Collect();
            flowLayoutPanel1.WrapContents = true;
            flowLayoutPanel1.AutoScroll = true;
            for (int i = 0; i < listF.Count; i++)
            {
                //FileInfo fi = new FileInfo(fileName);
                //using (Image objImage = Image.FromFile(newDirectory + "\\" + listF[i] + ".JPG"))

                string Sr = listF[i];
                if (Sira.ContainsKey(Sr))
                    if (Sira[Sr].Kategori == selKategori ||
                    Sira[Sr].AksSeriId == selSeri)
                    {
                        FileStream fs = new FileStream(newDirectory + "\\" + Sr + ".JPG", FileMode.Open, FileAccess.Read);
                        Image objImage = System.Drawing.Image.FromStream(fs);

                        /*
                        PictureBox picture = new PictureBox
                        {
                            Name = Sr,
                            //Tag = Sira[Sr].AksSeriId.ToString(),
                            Size = new Size(objImage.Width, objImage.Height),
                            Location = new Point(0, 0),
                            Image = objImage,
                            SizeMode = PictureBoxSizeMode.CenterImage
                        };
                        */


group1.Items.Add(new GalleryItem(objImage, Sr, Sira[Sr].AksesuarId.ToString()));





                        /*
                        PictureEdit picture = new DevExpress.XtraEditors.PictureEdit();
                        picture.Width = objImage.Width;
                        picture.Height = objImage.Height;
                        picture.Image = objImage;
                        picture.Properties.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
                        picture.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Zoom;

                        x++;
                        new ToolTip().SetToolTip(picture, Sira[Sr].AksesuarId.ToString());
                        flowLayoutPanel1.Controls.Add(picture);
                        */

                        fs.Close();
                        fs.Dispose();
                    }
                //PictureEdit Pedit = new DevExpress.XtraEditors.PictureEdit();
                //Pedit.Width = objImage.Width;
                //Pedit.Height = objImage.Height;
                //flowLayoutPanel1.Controls.Add(Pedit);
                //Pedit.Image = objImage;
                //Pedit.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Clip;


                //If FlowPanel Is flowR Then
                //    AddHandler Pedit.MouseClick, AddressOf Pedit_MouseClick
                //    AddHandler Pedit.MouseEnter, AddressOf Pedit_MouseEnter
                //    AddHandler Pedit.MouseLeave, AddressOf Pedit_MouseLeave
                //End If
            }

        }

        void btnCrop_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listF.Count; i++)
            {
                string idx = listF[i];
                //using (Image img = Image.FromFile(targetDirectory + "\\" + idx + ".JPG"))
                {
                    FileStream fs = new FileStream(targetDirectory + "\\" + listF[i] + ".JPG", FileMode.Open, FileAccess.Read);
                    Image objImage = System.Drawing.Image.FromStream(fs);

                    //TODO: listR[idx]'yi 3'er pixel genişlet her yönde!
                    KalikoImage sharpimg = new KalikoImage(Crop(objImage, listR[idx]));
                    sharpimg = sharpimg.Scale(new FitScaling(32, 32));
                        //.Resize(sharpimg.Width / 3, sharpimg.Height / 3);
                    sharpimg.ApplyFilter(new UnsharpMaskFilter(1.2F, 0.5F, 20));   //threshold: http://www.damiensymonds.com.au/tut_usm.html
                    sharpimg.SaveJpg(newDirectory + "\\" + idx + ".JPG", 100);
                    sharpimg.Dispose();

                    fs.Close();
                    fs.Dispose();

                    float hue;
                    using (FileStream s = new FileStream(newDirectory + "\\" + idx + ".JPG", FileMode.Open))
                    {
                        Bitmap img = (Bitmap)Image.FromStream(s);
                        if (img != null)
                        {
                            hue = GetDominantColor(img).GetHue();
                            using (StreamWriter writer = new StreamWriter(hueDirectory + "\\" + idx + ".txt", true))
                            {
                                writer.WriteLine(hue);
                            }
                        }
                    }
                }
            }
        }



        public Color GetDominantColor(Bitmap image)
        {
            if (image != null)
            {
                BitmapData bitmapData1 = image.LockBits(new Rectangle(0, 0,
                                         image.Width, image.Height),
                                         ImageLockMode.ReadOnly,
                                         PixelFormat.Format32bppArgb);

                int a = 0, r = 0, g = 0, b = 0;
                unsafe
                {
                    byte* imagePointer1 = (byte*)bitmapData1.Scan0;
                    for (int i = 0; i < bitmapData1.Height; i++)
                    {
                        for (int j = 0; j < bitmapData1.Width; j++)
                        {
                            a++;
                            b += imagePointer1[0];
                            g += imagePointer1[1];
                            r += imagePointer1[2];
                            imagePointer1 += 4;
                        }

                        //4 bytes per pixel
                        imagePointer1 += bitmapData1.Stride - (bitmapData1.Width * 4);
                    }

                }

                image.UnlockBits(bitmapData1);

                return Color.FromArgb(r / a, g / a, b / a);
            }
            return Color.Transparent;
        }



        public Image Crop(Image bmp, Rectangle cropRect)
        {
            Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
            using (Graphics g = Graphics.FromImage(target))
            {
                g.DrawImage(bmp, new Rectangle(0, 0, target.Width, target.Height),
                                 cropRect,
                                 GraphicsUnit.Pixel);
            }
            return (Image)target;
        }

    }
}
